package com.bridge.common.base;

import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.ImageView;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;
import com.bridge.baselibs.eventbus.EventBusUtil;
import com.bridge.baselibs.eventbus.EventMessage;
import com.bridge.common.R;
import com.bridge.common.dialog.VDialog;
import com.bridge.common.http.HttpManager;
import com.bridge.common.http.HttpUtils;
import com.bridge.common.http.ReqOptions;
import com.bridge.common.interfaces.IHttpCallback;
import com.bridge.common.utils.StatusBarUtil;
import com.bridge.common.utils.ToastshowUtils;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.lang.reflect.Field;
import java.util.HashMap;
import io.reactivex.Observable;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;

public abstract class BaseActivity extends AppCompatActivity implements IHttpCallback, View.OnClickListener {
    public BaseAppLication application;
    private static BaseActivity mForegroundActivity = null;
    /**
     * 添加水印
     * @param rootView 根布局
     * @param printText 要印的字
     */
    public void addWaterPrint(ViewGroup rootView, String printText) {
        ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT);
        ImageView imageView = new ImageView(this);
        imageView.setLayoutParams(params);
        imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
    }

    /**
     * 获取当前处于前台的activity
     */
    public static BaseActivity getForegroundActivity() {
        return mForegroundActivity;
    }

    /**
     * 获取状态栏的高度
     *
     * @return
     */
    public int getStatusBarHeight() {
        try {
            Class<?> c = Class.forName("com.android.internal.R$dimen");
            Object obj = c.newInstance();
            Field field = c.getField("status_bar_height");
            int x = Integer.parseInt(field.get(obj).toString());
            return getResources().getDimensionPixelSize(x);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    @Override
    public void onCreate(Bundle savedInstanceState){
        // 禁止截屏
//        SecureUtils.setFobiddenScreenShot(this);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
        beforSetContentView();
        AppManager.getAppManager().addActivity(this);
        setContentView(layoutId());

        initView();
        setListenner();

        if (isRegisterEventBus()) {
            EventBusUtil.register(this);
        }
        afterSetContentView();

        if (application == null) {
            // 得到Application对象
            application = (BaseAppLication) getApplication();
        }
        application.addActivity_(this);// 调用添加方法
        mForegroundActivity = this ;
    }

    public void afterSetContentView() {

    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    /**
     * 一般方法,可供在设置setContentView前做些操作
     */
    public void beforSetContentView() {
        StatusBarUtil.setStatusBarMode(this,true, R.color.home_bar_color);
    }


    @Override
    public void onClick(View view) {

    }

    @Override
    protected void onStop() {
        super.onStop();
        if (isRegisterEventBus()) {
            EventBusUtil.unregister(this);
        }
    }

    @Override
    protected void onDestroy() {
        AppManager.getAppManager().finishActivity(this);
        super.onDestroy();
    }

    /**
     * 获取bind对象
     * @param <T>
     * @return
     */
    public <T extends ViewDataBinding> T getBind() {
        return DataBindingUtil.setContentView(this, layoutId());
    }

    // 跳转至下个页面
    public void turnToActivity(Class className){
        Intent intent = new Intent(this,className);
        startActivity(intent);
    }

    // 跳转至下个页面并传参
    public void turnToActivity(Class className, Bundle bundle){
        Intent intent = new Intent(this,className);
        intent.putExtras(bundle);
        startActivity(intent);
    }

    // 跳转至下个页面并销毁
    public void turnToActivityWithFinish(Class className){
        Intent intent = new Intent(this,className);
        startActivity(intent);
        this.finish();
    }

    // 跳转至下个页面并传参，并销毁
    public void turnToActivityWithFinish(Class className, Bundle bundle){
        Intent intent = new Intent(this,className);
        intent.putExtras(bundle);
        startActivity(intent);
        this.finish();
    }


    /**
     * 发送请求
     * @param requestCode 请求码
     * @param call 请求体
     * @param lodingStr 加载文字提示(传空串“”弹出无文字弹窗，传null不弹出进度条)
     * @param callback 回调
     */
    public void doHttp(int requestCode, Observable<ResponseBody> call, String lodingStr, IHttpCallback callback) {
        HttpUtils.getInstance().doHttp(requestCode,call,lodingStr,callback);
    }

    /**
     * 进度条加载回调，可统一加载
     * @param requestCode
     * @param text
     */
    @Override
    public void onLoading(int requestCode,String text) {
        VDialog.getInstance().showLoadingDialog(text, this, true, true);
    }

    /**
     * 请求成功回调
     * @param requestCode 请求码
     * @param result
     *
     */
    @Override
    public void onSuccess(int requestCode, String result) {
        //不论返回多少条数据，data都应以一个集合的方式返回
    }

    /**
     * 请求成功，但状态码错误回调，可做统一处理（登录过期，账号禁用等）s
     * @param requestCode 请求码
     * @param msg 提示信息
     */
    @Override
    public void onFailure(int requestCode, String msg) {
        ToastshowUtils.showToastSafe(msg);
    }

    /**
     * 请求失败回调，可做统一操作（错误提示）
     * @param requestCode 请求码
     */
    @Override
    public void onError(int requestCode, String msg) {
        ToastshowUtils.showToastSafe(msg);
    }
    /**
     * 获取http请求body
     * @param options 附加参数
     * @param map 请求参数集合
     * @return
     */
    protected RequestBody getRqBody(HashMap map, ReqOptions options){
        return HttpManager.getRqBody(map,options);
    }

    /**
     * 是否注册事件分发
     *
     * @return true绑定EventBus事件分发，默认不绑定，子类需要绑定的话复写此方法返回true.
     */
    protected boolean isRegisterEventBus() {
        return false;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventBusCome(EventMessage event) {
        if (event != null) {
            receiveEvent(event);
        }
    }

    @Subscribe( sticky = true)
    public void onStickyEventBusCome(EventMessage event) {
        if (event != null) {
            receiveStickyEvent(event);
        }
    }

    /**
     * 接收到分发到事件
     *
     * @param event 事件
     */
    protected void receiveEvent(EventMessage event) {

    }

    /**
     * 接受到分发的粘性事件
     *
     * @param event 粘性事件
     */
    protected void receiveStickyEvent(EventMessage event) {

    }
    /***********************************EventBus  end***********************************/

    protected abstract int layoutId();
    protected abstract void initView();
    protected abstract void setListenner();
}
